<template>
  <div id="lg">
    <h3>小U后台管理系统</h3>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <el-input
          style="width: 400px"
          placeholder="请输入用户名"
          v-model.number="ruleForm.username"
        >
          <el-button slot="prepend" icon="el-icon-user"> </el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-form-item prop="password">
          <el-input
            style="width: 400px"
            placeholder="请输入密码"
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
            ><el-button slot="prepend" icon="el-icon-lock"></el-button
          ></el-input>
        </el-form-item>

        <el-button
          type="primary"
          style="width: 400px; margin-top: 20px"
          @click="submitForm('ruleForm')"
          >立即登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { adminLogin } from "../../request";
// 引入辅助函数mapMutations，mapActions要映射到methods中
// mapstate，mapGetters要映射到computed中
import {mapMutations}from 'vuex'
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      callback();
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };

    return {
      ruleForm: {
        username: "admin",
        password: "admin888",
      },
      rules: {
        username: [{ validator: checkAge, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  methods: {
    // 映射到mapMutations
    ...mapMutations({
      saveUserInfo:'saveUserInfo'                    
    }),
    // 点击按钮去登录，先校验，成功才发送请求。
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          console.log(this.ruleForm);
          let res = await adminLogin(this.ruleForm);
          
          this.saveUserInfo(res)
    
          alert("提交成功");
          this.$router.push("/layout");
        } else {
          console.log("提交失败!!");
          return false;
        }
      });
    },
  },
};
</script>
<style lang="">
html {
  background-image: url("../../image/bg.jpeg");
}
#lg h3 {
  padding-top: 20px;
  color: #fb6d49;
}
#lg {
  margin: 150px auto;
  width: 500px;
  height: 300px;
  background-color: white;
  text-align: center;
}
#lg form {
  margin: 0px;
}
#lg input {
  margin: auto;
}
#lg .el-form-item__error {
  left: 50px;
}
</style>
